#include "message.h"
#include "client.h"

 
void ubus_client::init_client(const char *client_path, const char  *server_path)
{
    unlink(client_path); 
	int len = 0;
    if ((client_fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0){  
        perror("client socket error");  
        exit(1);  
    }  

    memset(&client_un, 0, sizeof(client_un));  
    client_un.sun_family = AF_UNIX;  
    strcpy(client_un.sun_path, client_path);  
    len = offsetof(struct sockaddr_un, sun_path) + strlen(client_un.sun_path);  
	
    if (bind(client_fd, (struct sockaddr *)&client_un, len) < 0) {  
        perror("bind error");  
        exit(1);  
    }  
 
    memset(&server_un, 0, sizeof(server_un));  
    server_un.sun_family = AF_UNIX;  
    strcpy(server_un.sun_path, server_path);  
    len = offsetof(struct sockaddr_un, sun_path) + strlen(server_un.sun_path);  
    if (connect(client_fd, (struct sockaddr *)&server_un, len) < 0){  
        perror("connect error");  
        exit(1);
    }  
}

ubus_client::ubus_client(const char *client_path, const char  *server_path)
{
	init_client(client_path, server_path);
}

ubus_client::~ubus_client()
{
	close(client_fd);
}

bool ubus_client::set_read_head(char *sendinfo, int *sendinfo_size)
{
	if(sendinfo == NULL)
	{
		return false;
	}
	int size = sizeof(message);
	memcpy(sendinfo, &size, 4);
	memcpy(sendinfo + 4, &message, size);
	*sendinfo_size = size + 4;

	return true;
}

void ubus_client::set_message_head(char *info)
{	
	message.head_.type = 0x60;
	message.head_.len = strlen(info);
	strcpy(message.content,info);
}

void ubus_client::sendmessage(){

	char buff[1024] = {0};
	char sendinfo[1024] = {0};
	int infolen = 0;
   	for(int i = 0 ; i < 100; i++)
	{	
		memset(buff,0,sizeof(buff));
		memset(sendinfo, 0, sizeof(buff));
		sprintf(buff, "aaabbbccc %d", i);
		set_message_head(buff);
		set_read_head(sendinfo, &infolen);
		write(client_fd, sendinfo, infolen);

		int n = read(client_fd, buff, 1024);
		 
         if ( n < 0 ) {    
            printf("the other side has been closed.\n");    
         }else {
           message_ *p = reinterpret_cast<message_*>(buff);
		   printf("%d , %d , %s\n", p->head_.type, p->head_.len, p->content);
		   memset(buff, 0, sizeof(buff));
		   
         }    
    } 
}

int main(int argc, char* argv[]) {  

	const char *client_path = "client.socket";	
	const char *server_path = "server.socket";	

	ubus_client client(client_path, server_path);
	client.sendmessage();

	return 0;  
}
